//
//  BiGpsTrackViewController.m
//  TrunkIndustryManageSystem
//
//  Created by WT_lyy on 15/4/24.
//  Copyright (c) 2015年 李璐西. All rights reserved.
//

#import "BiGpsTrackViewController.h"
#import "Tracking.h"

#import "AnimatedAnnotation.h"
#import "AnimatedAnnotationView.h"
#import "BiCustomerInfo.h"
#import "CustomAnnotationView.h"
@interface BiGpsTrackViewController ()<MAMapViewDelegate, TrackingDelegate>{

    Tracking * _track;
    
    NSArray * locArr;
}

@property (nonatomic,strong) MAMapView * mapView;

@property (nonatomic,strong)  MAPointAnnotation *startAnnotation;
@end

@implementation BiGpsTrackViewController


/* 构建mapView. */
- (void)setupMapView
{
    
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, [self viewTop], MAIN_SCREEN_WIDTH, MAIN_SCREEN_HEIGHT-[self viewTop])];
    self.mapView.delegate = self;
    self.mapView.distanceFilter = FILTER_DISTANCE;
    self.mapView.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    self.mapView.pausesLocationUpdatesAutomatically = NO;
    [self.view addSubview:self.mapView];

}


/* 构建轨迹回放. */
- (void)setupTracking
{

        NSString * sqlStr = [NSString stringWithFormat:@"select * from table_track where systemNum=%@ order by creatdate asc",self.e_id];
        
        locArr = [NSArray arrayWithArray:[[DBManager sharedInstance] querryTable:sqlStr]];
        
        //如果数据库无数据，从网络请求gps列表
        if (locArr.count == 0 && self.isExecuted ==2) {
            
            NSDictionary *  paraDic = [NSDictionary dictionaryWithObjectsAndKeys:[BiUserEntity sharedInstance].userid,@"userId",self.e_id,@"sellId", nil];
            
            [[BiNetEngine shareInstance] requestSaleGetGPSInfo:self paraDict:paraDic];
            
            [self asyshowHUDView:WAITING CurrentView:self];
        }else{
            
            [self setTrackFromLoacArr];
        }

}

- (void)setTrackFromLoacArr{

    CLLocationCoordinate2D polylineCoords[locArr.count];
    
    for (int i =0; i < locArr.count; i ++) {
        NSDictionary * clDict = locArr[i];
        
        polylineCoords[i].latitude = [clDict[@"latitude"] doubleValue];
        
        polylineCoords[i].longitude = [clDict[@"longitude"] doubleValue];
    }
    
    /* 构建tracking. */
    _track = [[Tracking alloc] initWithCoordinates:polylineCoords count:locArr.count];
    _track.delegate = self;
    _track.mapView  = self.mapView;
    _track.duration = 1.f;
    _track.edgeInsets = UIEdgeInsetsMake(50, 50, 50, 50);
}

- (void)dealloc{

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavBackBtn];
    
    [self setNavBarWithHidden:NO];
    
    [self setNavBarTitle:@"GPS轨迹图查看"];
    
    [self setupMapView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:UIApplicationWillEnterForegroundNotification object:nil];
}


- (void)handleNotification:(NSNotification *)notification{

    if (0== self.isExecuted) {
        
        
    }else{
    
        _track = nil;
        
        if (!_track) {
            
            [self setupTracking];
        }
        
        [_track execute];
    }

}

- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    
    if (0 == self.isExecuted) {
        
        MACoordinateSpan span;
        MACoordinateRegion region;
        
        span.latitudeDelta = 0.300;
        span.longitudeDelta = 0.300;
        region.span = span;
        region.center = CLLocationCoordinate2DMake(self.polylineCoord.latitude, self.polylineCoord.longitude);
        
        [self.mapView setRegion:[_mapView regionThatFits:region] animated:YES];
        
        self.startAnnotation = [[MAPointAnnotation alloc] init];
        self.startAnnotation.coordinate = self.polylineCoord;
        [self.mapView setCenterCoordinate:self.polylineCoord];
        [self.mapView addAnnotation:self.startAnnotation];
    }else{
        if (!_track) {
            
            [self setupTracking];
        }
        
        [_track execute];
    }
}

#pragma mark - TrackingDelegate

- (void)willBeginTracking:(Tracking *)tracking
{

    CLLocationCoordinate2D  cornate;
    
    if (0 == self.isExecuted) {
        cornate = self.polylineCoord;
        
    }else{
    
        NSDictionary * clDict = locArr[0];

       cornate = CLLocationCoordinate2DMake([clDict[@"latitude"] doubleValue], [clDict[@"longitude"] doubleValue]);
    }
    
    [self addAnnotationWithCoordinate:cornate withInfo:nil index:0];
    
}

- (void)didEndTracking:(Tracking *)tracking
{
    
    //客户anno
    if (self.isExecuted != 0) {
        
        for (int i = 0 ; i<self.cusTomerArr.count ;i++) {
            
            BiCustomerInfo * info = self.cusTomerArr[i];
            
            CLLocationCoordinate2D  cornate = CLLocationCoordinate2DMake([info.latitude doubleValue], [info.longitude doubleValue]);
            
            [self addAnnotationWithCoordinate:cornate withInfo:info index:1];
        }
    }
    
    if (self.isExecuted == 2) {
        NSDictionary * clDict = [locArr lastObject];
        
        CLLocationCoordinate2D  cornate = CLLocationCoordinate2DMake([clDict[@"latitude"] doubleValue], [clDict[@"longitude"] doubleValue]);
        
        [self addAnnotationWithCoordinate:cornate withInfo:nil index:2];
    }
}


#pragma mark - Utility

//index 0 起点  1客户  2终点
-(void)addAnnotationWithCoordinate:(CLLocationCoordinate2D)coordinate withInfo:(BiCustomerInfo *)info index:(NSInteger)index
{
    NSMutableArray *trainImages = [[NSMutableArray alloc] init];

    AnimatedAnnotation * anni = [[AnimatedAnnotation alloc] initWithCoordinate:coordinate];
    if (info) {
        anni.title          = info.customerName;
        anni.subtitle       = info.customerPhone;
    }
//    if (0 == index) {
//        [trainImages addObject:LOAD_IMAGE_WITH_CACHE(@"CarSale/icon_main_start")];
//
//    }else if (1 == index){
//    
//        [trainImages addObject:LOAD_IMAGE_WITH_CACHE(@"CarSale/icon_main_ke")];
//
//    }else if (2 == index){
//    
//        [trainImages addObject:LOAD_IMAGE_WITH_CACHE(@"CarSale/icon_main_end")];
//
//    }
    
    anni.animatedImages = trainImages;
    
    [self.mapView addAnnotation:anni];
    
    if (info) {
        [self.mapView selectAnnotation:anni animated:YES];
    }
    
}

#pragma mark - MAMapViewDelegate

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[AnimatedAnnotation class]])
    {
        static NSString *animatedAnnotationIdentifier = @"AnimatedAnnotationIdentifier";
        
        AnimatedAnnotationView *annotationView = (AnimatedAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:animatedAnnotationIdentifier];
        
        if (annotationView == nil)
        {
            annotationView = [[AnimatedAnnotationView alloc] initWithAnnotation:annotation
                                                                reuseIdentifier:animatedAnnotationIdentifier];
            
            annotationView.canShowCallout   = YES;
            annotationView.draggable        = YES;
           // annotationView.image = nil;
        }
        
        return annotationView;
    }else if([annotation isKindOfClass:[MAPointAnnotation class]]){
    
        static NSString *customReuseIndetifier = @"customReuseIndetifier";
        
        CustomAnnotationView *annotationView = (CustomAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        
        if (annotationView == nil)
        {
           
            
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            // must set to NO, so we can show the custom callout view.
            annotationView.canShowCallout = NO;
            annotationView.draggable = YES;

        }
        
        UIImage * image = LOAD_IMAGE_WITH_CACHE(@"CarSale/icon_main_start");
        
        annotationView.portrait = image;
        
        return annotationView;
    }
    
    return nil;
}

- (MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id <MAOverlay>)overlay
{
    if (overlay == _track.polyline)
    {
        MAPolylineView *polylineView = [[MAPolylineView alloc] initWithPolyline:overlay];
        
        polylineView.lineWidth   = 6.f;
        polylineView.strokeColor = UIColorFromRGB(BLUE_COLOR_VALUE);
        
        return polylineView;
    }
    
    return nil;
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation{

    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude);
    [self.mapView setCenterCoordinate:coordinate animated:YES];
}

//- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
//{
//    NSLog(@"%@ ----- %@", self, NSStringFromSelector(_cmd));
//    
//    CLLocation *location = [[CLLocation alloc] initWithLatitude:userLocation.coordinate.latitude
//                                                      longitude:userLocation.coordinate.longitude];
//    // check the zero point
//    if  (userLocation.coordinate.latitude == 0.0f ||
//         userLocation.coordinate.longitude == 0.0f)
//        return;
//    
//    // check the move distance
//    if (_points.count > 0) {
//        CLLocationDistance distance = [location distanceFromLocation:_currentLocation];
//        if (distance < 5)
//            return;
//    }
//    
//    if (nil == _points) {
//        _points = [[NSMutableArray alloc] init];
//    }
//    
//    [_points addObject:location];
//    _currentLocation = location;
//    
//    NSLog(@"points: %@", _points);
//    
//    [self configureRoutes];
//    
//    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude);
//    [self.mapView setCenterCoordinate:coordinate animated:YES];
//}

- (void)mapView:(MAMapView *)mapView didAddOverlayViews:(NSArray *)overlayViews{

}


#pragma -mark Net Delegate
- (void)onNetEngineResponse:(int)tag entity:(id)entity userInfo:(NSDictionary *)userInfo
{
    [self removeHUDView:self];
    
    NSDictionary * dict = (NSDictionary *)entity;
    
    [self showMessage:dict[@"result_info"]];
    
    
    if ([dict[@"response_status"] integerValue] != 200) {
        
        return;
        
    }
    
    locArr = dict[@"data"];
    
    [self setTrackFromLoacArr];
    
}

- (void)onNetEngineResponseFail:(int)tag entity:(id)entity userInfo:(NSDictionary *)userInfo
{
    [self removeHUDView:self];
    
}

@end
